import React, { Component } from 'react';
import FontIcon from 'material-ui/FontIcon';
import RaisedButton from 'material-ui/RaisedButton';

import CONFIG from '../../config';
import Tweet from '../Home/Tweet';
import Delete from '../Utils/Delete';
import NewActivity from '../Activity/NewActivity';
import ShowPeoplePanel from './ShowPeoplePanel';
import ShowCommentPanel from './ShowCommentPanel';
import ShowActivityPanel from './ShowActivityPanel';
import { timeToZNCHStr } from '../Utils/Helper';
import { parseJSON, getMethod, postJsonMethod } from '../../redux/Helper';

export default class Show extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      // 是否参加了当前活动
      isParticipant: false,
      // 是否为发布者
      isPublisher: false,
      // 是否成功获取数据
      isFetchData: false,
      openNewActivity: false,
      openDelete: false,
      openTweet: false
    };
  }

  componentWillMount() {
    this.initFetch();
  }

  componentDidMount() {
    window.addEventListener('reloadActivityFromMe', this.handleReloadEvent, false);
  }

  componentWillUnmount() {
    window.removeEventListener('reloadActivityFromMe', this.handleReloadEvent, false);
  }

  /**
   * 收到重载事件
   */
  handleReloadEvent = () => {
    this.initFetch();
  };

  /**
   * 获取初始数据
   * 判断是否为活动参与者和发布者
   */
  initFetch = () => {
    let id = this.props.params.id;
    let request = `?token=${this.props.token}`;
    let url = `${CONFIG.apiHost}/api/activity/show/${id}${request}`;

    fetch(url, getMethod)
    .then(parseJSON)
    .then(res => {
      let isPublisher = false;

      if (res.msg.user_id == this.props.userId) {
        isPublisher = true;
      }

      this.setState({
        data: res.msg,
        isParticipant: res.msg.is_join_activity,
        isPublisher: isPublisher,
        isFetchData: true
      });
    })
  };

  /**
   * 打开会话框
   */
  handleOpen = (n, e) => {
    this.setState({[n]: true});
  };

  /**
   * 关闭会话框
   */
  handleClose = (n, e) => {
    this.setState({[n]: false});
  };

  /**
   * 保存message
   */
  handleMessage = (v, e) => {
    this.setState({snackbarMessage: v});
  };

  /**
   * 确认删除
   */
  deleteConfirm = (v, e) => {
    if (v) {
      let url = CONFIG.apiHost + '/api/activity/delete/' + this.state.data.id + '?token=' + this.props.token;
      let postData = {user_id: this.props.userId};

      fetch(url, postJsonMethod(postData))
      .then(parseJSON)
      .then(res => {
        if (res.status) {
          this.props.replaceTo('/activity/me');
        }
      })
    }
  };

  /**
   * 更新重新获取数据
   */
  refresh = () => {
    this.initFetch();
  };

  /**
   * 申请和取消申请活动
   */
  changeInActivity = (value) => {
    let obj = this.state.data;
    obj.is_apply_activity = value;
    
    this.setState({
      data: obj
    });
  };

  render() {
    let commentPanel = (
      <ShowCommentPanel
        data={this.state.data}
        token={this.props.token}
        userId={this.props.userId}
        userImg={this.props.userImg}
        userName={this.props.userName}
        color500={this.props.color500}
        isPublisher={this.state.isPublisher}
        isParticipant={this.state.isParticipant}
        handleOpen={this.handleOpen}
        changeInActivity={this.changeInActivity}
      />
    );

    let activityPanel = (
      <ShowActivityPanel
        data={this.state.data}
        isPublisher={this.state.isPublisher}
        handleOpen={this.handleOpen}
      />
    );

    let peoplePanel = (
      <ShowPeoplePanel
        data={this.state.data}
        token={this.props.token}
        userId={this.props.userId}
        isPublisher={this.state.isPublisher}
        pushTo={this.props.pushTo}
      />
    );

    let otherPanels = [
      <Delete
        key={0}
        open={this.state.openDelete}
        isSmallViewport={this.props.isSmallViewport}
        handleClose={this.handleClose.bind(this, 'openDelete')}
        deleteConfirm={this.deleteConfirm}
      />,
      <NewActivity
        key={1}
        method={'edit'}
        data={this.state.data}
        token={this.props.token}
        userId={this.props.userId}
        userImg={this.props.userImg}
        color500={this.props.color500}
        open={this.state.openNewActivity}
        tokenExpired={this.props.tokenExpired}
        isSmallViewport={this.props.isSmallViewport}
        handleClose={this.handleClose.bind(this, 'openNewActivity')}
      />,
      <Tweet
        key={2}
        open={this.state.openTweet}
        token={this.props.token}
        color500={this.props.color500}
        userId={this.props.userId}
        activityId={this.state.data.id}
        isSmallViewport={this.props.isSmallViewport}
        handleClose={this.handleClose.bind(this, 'openTweet')}
        handleOpenSnackbar={this.props.handleOpenSnackbar}
      />
    ];

  	return (
  	  <div>
        {this.state.isFetchData ? 
          <div className='row'>
            <div className='col-md-8 col-sm-6 col-xs-12 card-line show-card-left'>
              {commentPanel}
            </div>
            <div className='col-md-4 col-sm-6 col-xs-12 show-card-right'>
              {activityPanel}
              {peoplePanel}
            </div>
            {otherPanels}
          </div>
          : ''
        }
  	  </div>
  	);
  }
};